package com.example.demo.server;

import com.example.demo.cache.ChannelMap;
import com.example.demo.model.Result;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName: NettyServer
 * @Author: huangzf
 * @Date: 2018/9/25 15:40
 * @Description:
 */
@Slf4j
public class NettyServer {

    private NettyServerChannelInitializer serverChannelInitializer = null;

    private int port = 8000;


    public void bind() throws Exception {
        //配置服务端的NIO线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            serverChannelInitializer = new NettyServerChannelInitializer();
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                //保持长连接
                .childOption(ChannelOption.SO_KEEPALIVE,true)
                .option(ChannelOption.SO_BACKLOG, 1024)
                .childHandler(serverChannelInitializer);

            //绑定端口，同步等待成功
            ChannelFuture f = b.bind(port).sync();


            //等待服务器监听端口关闭
            f.channel().closeFuture().sync();
        } finally {
            //释放线程池资源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public Result write(Object obj, String tenantId ,String uniId) throws Exception {
        // 获取锁
        Lock lock = ChannelMap.getChannelLock(tenantId);
        try {
            Channel channel = ChannelMap.getChannel(tenantId);
            if(channel != null){
                lock.lock();
                if(channel.isOpen()){
                    // 设置同步
                    CountDownLatch latch = new CountDownLatch(1);
                    NettyServerHandler nettyServerHandler = (NettyServerHandler) channel.pipeline().get("handler");
                    nettyServerHandler.resetSync(latch,1);
                    nettyServerHandler.setUnidId(uniId);
                    channel.writeAndFlush(obj );
                    //同步返回结果
                    if (latch.await(60,TimeUnit.SECONDS)){
                        // printerServerHandler.setTimeout(0);
                        return nettyServerHandler.getResult();
                    }
                    //如果超时，将超时标志设置为1
                    //printerServerHandler.setTimeout(1);
                    log.error("请求超时60s");
                    return new Result(2,"请求超时",null);
                }else{
                    return new Result(0,"客户端已关闭!",null);
                }
            }

        }catch (Exception e){
            e.printStackTrace();
            return new Result(0,"服务出错!",null);

        }finally {
            if (lock != null){
                lock.unlock();
            }
        }
        return new Result(0,"客户端没有连接!",null);
    }

    public static void main(String[] args) throws Exception {
       new  NettyServer().bind();
    }

}
